package com.a8hcoffee.zxingdemo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import zxing.android.ZUtils;

import com.google.zxing.Result;

public class WebActivity extends AppCompatActivity implements View.OnClickListener {

    private WebView mWebView;
    private ProgressBar mProgressBar;
    private RelativeLayout rootLayout;

    //顶部
    private ImageView iv_right_web;
    private ImageView iv_back_web;
    private TextView tv_title_web;

    //判断网页加载是否错误
    private boolean isInErrorState = false;

    //错误页
    private LinearLayout mEmptyView;
    private TextView tv_error_msg;

    //二维码解析到的字符串
    private String mEQResult = "";
    //长按dialog
    private CustomDialog mCustomDialog;
    private ArrayAdapter<String> adapter;
    //网页图片保存到的bitmap
    private Bitmap bitmap;

    private static final int QR_CODE_TRUE = 1;
    private static final int QR_CODE_FALSE = 2;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case QR_CODE_TRUE:
                    if (adapter != null){
                        adapter.add("识别图中二维码");
                        adapter.notifyDataSetChanged();
                    }
                    break;
                //不是二维码图片
                case QR_CODE_FALSE:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        initViews();
        initWeb();

        Intent intent = getIntent();
        String path = intent.getStringExtra("path");
        if (!TextUtils.isEmpty(path)) {
            mWebView.loadUrl(path);
        }

    }

    private void initWeb() {
        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadsImagesAutomatically(true);
        //启用地理定位
        mWebSettings.setGeolocationEnabled(true);
        //设置可以访问文件
        mWebSettings.setAllowFileAccess(true);
        //支持JS
        mWebSettings.setJavaScriptEnabled(true);
        //网页保存数据到LocalStorage
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        String appCachePath = this.getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(appCachePath);
        //当前webView显示网页
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                isInErrorState = true;
                mEmptyView.setVisibility(View.VISIBLE);
                mWebView.setVisibility(View.GONE);
                mEmptyView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isInErrorState = false;
                        mWebView.reload();
                    }
                });
                tv_error_msg.setText("错误信息:" + description);
                tv_title_web.setText("网络已断开");
            }
        });
        //progress
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress >= 35) {
                    //是否加载错误页面
                    if (!isInErrorState) {
                        mEmptyView.setVisibility(View.GONE);
                        mWebView.setVisibility(View.VISIBLE);
                    } else {
                        mEmptyView.setVisibility(View.VISIBLE);
                        mWebView.setVisibility(View.GONE);
                        tv_title_web.setText("网络已断开");
                    }
                }
                if (newProgress >= 90) {
                    mProgressBar.setVisibility(View.GONE);
                } else {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                tv_title_web.setText(title);
            }
        });
        //下载监听
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        //长按菜单
        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult result = ((WebView) v).getHitTestResult();
                if (null != result) {
                    int type = result.getType();
                    if (type == WebView.HitTestResult.IMAGE_TYPE
                            || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                        final String imageUrl = result.getExtra();

                        //开线程下载解析图片
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                bitmap = Utils.getBitmap(WebActivity.this, imageUrl);
                                Result result = ZUtils.parseQRcodeBitmap(bitmap);

                                if (result == null)
                                    handler.sendEmptyMessage(QR_CODE_FALSE);
                                else {
                                    mEQResult = result.getText();
                                    handler.sendEmptyMessage(QR_CODE_TRUE);
                                }
                            }
                        }).start();
                    }
                    showDialog();
                }
                return false;
            }
        });
    }

    private void initViews() {
        rootLayout = (RelativeLayout) findViewById(R.id.layout_web);

        //右侧更多
        iv_right_web = (ImageView) findViewById(R.id.iv_right);
        if (iv_right_web.getVisibility() == View.GONE)
            iv_right_web.setVisibility(View.VISIBLE);
        iv_right_web.setImageResource(R.mipmap.more);

        iv_back_web = (ImageView) findViewById(R.id.iv_back);
        //设置回退按钮，点击事件
        iv_back_web.setOnClickListener(this);

        tv_title_web = (TextView) findViewById(R.id.tv_title);
        tv_title_web.setText("加载中...");

        mWebView = (WebView) findViewById(R.id.webView_web);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar_web);

        //tv_error_msg
        tv_error_msg = (TextView) findViewById(R.id.tv_error_msg);
        mEmptyView = (LinearLayout) findViewById(R.id.empty_view_root);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解决WebView页面中播放了音频,退出Activity后音频仍然在播放的问题
        if (mWebView != null) {
            rootLayout.removeView(mWebView);
            mWebView.destroy();
        }

        //bitmap回收
        if(bitmap != null && !bitmap.isRecycled()){
            bitmap.recycle();
            bitmap = null;
        }
        System.gc();
    }

    @Override
// 设置回退
// 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_right:

                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * 显示Dialog
     * param v
     */
    private void  showDialog() {
        initAdapter();
        mCustomDialog = new CustomDialog(this) {
            @Override
            public void initViews() {
                // 初始CustomDialog化控件
                ListView mListView = (ListView) findViewById(R.id.lv_dialog);
                mListView.setAdapter(adapter);
                mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // 点击事件
                        switch (position) {
                            case 0:
                                //把图片发送给好友
                                sendToFriends();
                                closeDialog();
                                break;
                            case 1:
                                if (bitmap != null){
                                    String img_path = Utils.saveImageToGallery(WebActivity.this,bitmap);
                                    Toast.makeText(WebActivity.this,"图片保存在:"+img_path,Toast.LENGTH_SHORT).show();
                                }
                                closeDialog();
                                break;
                            case 2:
                                Toast.makeText(WebActivity.this, "已收藏(模拟)", Toast.LENGTH_SHORT).show();
                                closeDialog();
                                break;
                            case 3:
                                if(mEQResult != null){
                                    if (mEQResult.startsWith("http://weixin.qq.com") ||
                                            mEQResult.startsWith("https://weixin.qq.com")){
                                        showQrResult("识别出的是微信二维码，请用微信客户端打开",null);
                                    }else if ( mEQResult.startsWith("http://")
                                            || mEQResult.startsWith("https://")){
                                        mWebView.loadUrl(mEQResult);
                                    }else {
                                        showQrResult(mEQResult,null);
                                    }
                                }
                                closeDialog();
                                break;
                        }
                    }
                });
            }
        };
        mCustomDialog.show();
    }

    /**
     * 初始化对话框list数据
     */
    private void initAdapter() {
        adapter = new ArrayAdapter<>(this, R.layout.item_dialog);
        adapter.add("发送给朋友");
        adapter.add("保存到手机");
        adapter.add("收藏");
    }

    /**
     * 发送给好友
     */
    private void sendToFriends() {
        if (bitmap != null){
            Intent intent=new Intent(Intent.ACTION_SEND);
            File file = new File(Utils.saveImageToGallery(this,bitmap));
            Uri imageUri=  Uri.parse(file.getAbsolutePath());
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_STREAM, imageUri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(Intent.createChooser(intent, getTitle()));
        }
    }

    /**
     * 显示二维码识别结果
     */
    private void showQrResult(String result, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("识别结果");
        builder.setMessage(result);
        builder.setPositiveButton(R.string.button_ok, listener);
//        builder.setOnCancelListener(new FinishListener(this));
        builder.show();
    }

}
